<template>
  <a-row style="padding-bottom: 3%">
    <div style="padding-left: 3%">
      <a-tag color="red"> {{ redisname }}</a-tag>
    </div>
    <div style="padding-left: 3%">
      <a-tag color="green"> 定时刷新</a-tag>
    </div>
    <div>
      <a-switch
        v-model:checked="checked3"
        checked-children="开"
        un-checked-children="关"
      />
    </div>
    <div style="padding-left: 3%">
      <a-col>
        <a-input-search
          v-model:value="searchValue"
          placeholder="筛选value"
          style="width: 200px"
          @search="getonSearch(100)"
        />
      </a-col>
    </div>
    <div style="padding-left: 3%">
      <a-time-range-picker
        status="warning"
        :placeholder="placeholder"
        :defaultValue="selectedRange"
        @change="handleTimeChange"
        :allowClear="false"
      />
    </div>
    <div style="padding-left: 3%">
      <!-- <a-button @click="toggleFullscreen(true)"> -->
      <a-button @click="logopen = true">
        <template #icon>
          <FullscreenOutlined />
        </template>
      </a-button>
    </div>
  </a-row>

  <div
    style="text-align: left; padding-bottom: 3%; flex: 8; height: 100%"
    :class="{ fullscreen: isFullscreen }"
  >
    <div style="padding-left: 1%; padding-bottom: 0.5%" v-if="isFullscreen">
      <a-button @click="toggleFullscreen(true)">
        <template #icon>
          <FullscreenExitOutlined />
        </template>
      </a-button>
    </div>
    <div id="scrolldIV" class="scrolldIV">
      <template v-for="(item, index) in code" :key="index">
        <div id="group">
          <div class="leftDiv">{{ index }}</div>
          <div
            class="textDiv"
            :style="
              item.includes('ERROR')
                ? { color: 'red' }
                : {} && item.includes('WARNING')
                ? { color: `rgb(241, 250, 140)` }
                : {} && item.includes('SUCCESS')
                ? { color: `rgb(241, 250, 140)` }
                : {} && item.includes('INFO')
                ? { color: `rgb(242, 245, 239)` }
                : {} && item.includes('Crawl')
                ? { color: `rgb(241, 250, 140)` }
                : {} && item.includes('Traceback')
                ? { color: 'red' }
                : {}
            "
            v-html="item"
          ></div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import "codemirror/theme/dracula.css";
import axios from "axios";
import { useRoute } from "vue-router";

import dayjs from "dayjs";
import {
  FullscreenOutlined,
  FullscreenExitOutlined,
} from "@ant-design/icons-vue";

export default {
  components: {
    FullscreenOutlined,
    FullscreenExitOutlined,
  },
  data() {
    return {
      route: useRoute().params.itemName,
      dbname: "",
      redisname: "",
      password: "",
      host: "",
      searchValue: "",
      checked: "",
      checked3: false,
      placeholder: ["开始时间", "结束时间"],
      selectedRange: [
        dayjs("2000-01-01T00:00:00"),
        dayjs("2000-01-01T23:59:59"),
      ],
      code: [`====================财税日志==================== `],
      content: "",
      isFullscreen: false,
      logopen: false,
    };
  },
  methods: {
    toggleFullscreen(e) {
      if (e) {
        this.isFullscreen = !this.isFullscreen;
      }
    },
    handleTimeChange(value) {
      // 处理时间范围的变化
      const formattedValue = value.map((date) => date.format("HH:mm:ss"));
      console.log("Selected Time Range:", formattedValue);
    },
    getonSearch(limit = null) {
      this.code = [];
      if (this.searchValue) {
        this.onSearch(limit);
      } else {
        this.GetLog();
      }
    },

    onSearch(limit = null) {
      axios
        .post("/api/logs/search", {
          search: this.searchValue,
          limit: limit,
          LogName: this.redisname,
          db: this.dbname,
          password: this.password,
          host: this.host,
        }) // 发送GET请求到后端API
        .then((response) => {
          var json_list = response.data.data.log;
          // 逐块连接字符串
          for (var i = 0; i < json_list.length; i += 1) {
            var block = JSON.stringify(json_list[i].data)
              .replace(/\\n/g, "<br/>")
              .replace(/ /g, "&nbsp;")
              .slice(1, -1);
            if (!this.code.includes(block)) {
              this.code.push(block);
            }
          }
          this.sroldiv();
        });
    },
    GetLog(page = 5000) {
      axios
        .post("/api/logs", {
          db: this.dbname,
          host: this.host,
          page: page,
          password: this.password,
          LogName: this.redisname,
        }) // 发送GET请求到后端API
        .then((response) => {
          var json_list = response.data.data.log;
          // 逐块连接字符串
          for (var i = 0; i < json_list.length; i += 1) {
            var block = JSON.stringify(json_list[i])
              .replace(/\\n/g, "<br/>")
              .replace(/ /g, "&nbsp;")
              .slice(1, -1);
            if (!this.code.includes(block)) {
              this.code.push(block);
            }
          }
          this.sroldiv();
        })
        .catch((error) => {
          // 处理请求错误
          console.log(error);
        });
    },
    startTimer() {
      if (this.searchValue) {
        this.code = [];
        this.timer = setInterval(() => {
          // 定时器逻辑
          this.onSearch(100);
        }, 3141);
      } else {
        this.timer = setInterval(() => {
          this.GetLog(100);
        }, 3141);
      }
    },
    stopTimer() {
      clearInterval(this.timer); // 关闭定时器
    },
    sroldiv() {
      const div = document.getElementById("scrolldIV");
      setTimeout(() => {
        div.scrollTop = div.scrollHeight - div.clientHeight;
      }, 0);
    },
    changeselt(e) {
      this.logSelectedValue = e;
      this.GetLog();
    },
  },
  created() {
    this.redisname = this.$route.query.name;
    this.host = this.$route.query.host;
    this.dbname = this.$route.query.db;
    this.password = this.$route.query.password;
    console.log(this.redisname, this.host, this.route);
    this.GetLog();
  },
  beforeUnmount() {
    // 在页面退出之前关闭定时器
    clearInterval(this.timer);
  },
  watch: {
    checked3(value) {
      if (value) {
        // 当开关打开时，启动定时器
        this.startTimer();
      } else {
        // 当开关关闭时，关闭定时器
        this.stopTimer();
      }
    },
  },
};
</script>
<style>
#scrolldIV {
  width: 100%;
  overflow-y: scroll;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  border-radius: 4px;
  height: 600px;
  white-space: nowrap;
  text-align: left;
  background-color: rgb(40, 42, 54);
  color: rgb(248, 248, 242);
}
.textDiv {
  padding-right: 2%;
  width: 80%;
  font-size: 13px;
  word-wrap: break-word;
}

.leftDiv {
  width: auto;
  min-width: 50px;
  max-width: 100px;
  text-align: right;
  color: rgb(109, 138, 136);
  padding-right: 1%;
}

#group {
  display: flex;
}
</style>
